package com.edu.hre.struts.action.recruit;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreJobVacancy;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.sql.recruit.CandidateDAOService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.recruit.CandidateForm;
import com.edu.hre.struts.form.recruit.RecommendedCandidateForm;

public class RecommendedCandidateAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(RecommendedCandidateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final CandidateDAOService candidateDAOService = BeanFinder.getBean(CandidateDAOService.BEAN_NAME, CandidateDAOService.class);
	private final String ACTION_NAME = "recommendedCandidate";
 
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Print source code location.
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		
		int vacId = CommonUtils.getIntParameter("vacId", request);

		RecommendedCandidateForm beanForm = (RecommendedCandidateForm) form;
		
		HreJobVacancy vac = baseService.getFirstPojo("id", Compare.EQUAL, vacId, null, null, 0, HreJobVacancy.class);
		if (vac == null) {
			beanForm.setVacancyName(StringConstants.BLANK);
		} else {
			beanForm.setVacancyName(vac.getName());
		}

		// Get the sortBy parameter to determine how the result list is sorted! Then get the list and return.
		String sortBy = RequestUtils.getParameterStr(request, "sort", null);
		if (sortBy != null) { 
			beanForm.setAsc(!beanForm.isAsc());
			CommonUtils.sortCollection(beanForm.getAllCandidates(), beanForm.isAsc(), sortBy);
			return mapping.findForward(ACTION_NAME);
		}

		// Paging the displaying list.
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		List<CandidateForm> listCandidateForm = candidateDAOService.getRecommendedCandidates(vacId, 50);
		int countEmp = listCandidateForm.size();

		beanForm.setTotalPage(CommonUtils.getTotalPage(countEmp));
		beanForm.setAllCandidates(listCandidateForm);

		ArrayList<HrePageInfo> allPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(countEmp));
		beanForm.setListPages(allPages);
		beanForm.setTotalItems(countEmp);

		return mapping.findForward(ACTION_NAME);
	}
}
